#include "ActionCreateKey.h"
#include "KeyManager.h"
#include "KeyManagerException.h"
#include "ContactsManager.h"

// Qt includes
#include <QFileInfo>

using namespace kryptos::cryptography;
using namespace kryptos::entities;

namespace kryptos { namespace actions {


ActionCreateKey::ActionCreateKey(KeyInfo keyinfo) : m_keyinfo(keyinfo)
{
}

ActionCreateKey::~ActionCreateKey()
{
}

bool ActionCreateKey::Prepare()
{
    return true;
}

bool ActionCreateKey::Cleanup()
{
    return true;
}

void ActionCreateKey::RunAction()
{
    emit actionStarted();
    _actionSucceeded = CreateKey();
    emit actionEnded(_actionSucceeded);

    return;
}

bool ActionCreateKey::CreateKey()
{
    try
    {
        KeyManager::instance().createAndStoreKey(m_keyinfo);
        ContactsManager::manager().addContactWithoutGroup(Contact(m_keyinfo));
    }
    catch (KeyManagerException& e)
    {
        emit actionError("Error creating key '" + QString(m_keyinfo.name().c_str()) + "(" + QString(m_keyinfo.email().c_str()) + ")'");
        return false;
    }
    catch (...)
    {
        emit actionError("Error creating key '" + QString(m_keyinfo.name().c_str()) + "(" + QString(m_keyinfo.email().c_str()) + ")'");
        return false;
    }

    return true;
}

}}
